using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data.Contexts;

namespace UniversalAdmin.Infrastructure.Repositories;

public class DocumentPermissionRepository : Repository<DocumentPermission>, IDocumentPermissionRepository
{
    public DocumentPermissionRepository(ApplicationDbContext context) : base(context)
    {
    }

    public async Task<IEnumerable<DocumentPermission>> GetByDocumentIdAsync(Guid documentId)
    {
        return await _context.DocumentPermissions
            .Where(dp => dp.DocumentId == documentId)
            .ToListAsync();
    }

    public async Task<IEnumerable<DocumentPermission>> GetByUserIdAsync(Guid userId)
    {
        return await _context.DocumentPermissions
            .Where(dp => dp.UserId == userId)
            .ToListAsync();
    }

    public async Task<IEnumerable<DocumentPermission>> GetByRoleIdAsync(Guid roleId)
    {
        return await _context.DocumentPermissions
            .Where(dp => dp.RoleId == roleId)
            .ToListAsync();
    }

    public async Task<bool> HasPermissionAsync(Guid documentId, Guid userId, PermissionType permissionType)
    {
        // 检查用户是否是文档创建者
        var document = await _context.Documents.FindAsync(documentId);
        if (document != null && document.CreatedBy == userId.ToString())
            return true;

        // 检查用户是否有直接权限
        var hasDirectPermission = await _context.DocumentPermissions
            .AnyAsync(dp =>
                dp.DocumentId == documentId &&
                dp.UserId == userId &&
                dp.PermissionType == permissionType);

        if (hasDirectPermission)
            return true;

        // 检查用户角色是否有权限
        var userRoles = await _context.UserRoles
            .Where(ur => ur.UserId == userId)
            .Select(ur => ur.RoleId)
            .ToListAsync();

        return await _context.DocumentPermissions
            .AnyAsync(dp =>
                dp.DocumentId == documentId &&
                userRoles.Contains(dp.RoleId) &&
                dp.PermissionType == permissionType);
    }

    public async Task<IEnumerable<Guid>> GetAccessibleDocumentIdsAsync(Guid userId, PermissionType permissionType)
    {
        // 获取用户创建的文档
        var createdDocumentIds = await _context.Documents
            .Where(d => d.CreatedBy == userId.ToString())
            .Select(d => d.Id)
            .ToListAsync();

        // 获取用户直接有权限的文档
        var directPermissionDocumentIds = await _context.DocumentPermissions
            .Where(dp => dp.UserId == userId && dp.PermissionType == permissionType)
            .Select(dp => dp.DocumentId)
            .ToListAsync();

        // 获取用户通过角色有权限的文档
        var userRoles = await _context.UserRoles
            .Where(ur => ur.UserId == userId)
            .Select(ur => ur.RoleId)
            .ToListAsync();

        var rolePermissionDocumentIds = await _context.DocumentPermissions
            .Where(dp => userRoles.Contains(dp.RoleId) && dp.PermissionType == permissionType)
            .Select(dp => dp.DocumentId)
            .ToListAsync();

        // 合并所有结果并去重
        return createdDocumentIds
            .Union(directPermissionDocumentIds)
            .Union(rolePermissionDocumentIds)
            .ToList();
    }

    public async Task DeleteByDocumentIdAsync(Guid documentId)
    {
        var permissions = await _context.DocumentPermissions
            .Where(dp => dp.DocumentId == documentId)
            .ToListAsync();

        _context.DocumentPermissions.RemoveRange(permissions);
        await _context.SaveChangesAsync();
    }
}